/*
 * This file is part of nettool4j.
 * 
 * rockframework is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * rockframework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>;.
 */
package net.woodstock.nettool4j.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;

import net.woodstock.nettool4j.AbstractRunnable;

public class TCPRedirect extends AbstractRunnable {

	private static final int	TIMEOUT	= 5000;

	private RedirectInfo		redirect;

	private ProxyInfo			proxy;

	public TCPRedirect(final RedirectInfo redirect) {
		super();
		this.redirect = redirect;
	}

	public TCPRedirect(final RedirectInfo redirect, final ProxyInfo proxy) {
		super();
		this.redirect = redirect;
		this.proxy = proxy;
	}

	@Override
	public void run() {
		try {
			this.getLogger().log(Level.INFO, "Creating socket");
			ServerSocket serverSocket = new ServerSocket(this.redirect.getListen());

			this.getLogger().log(Level.INFO, "Running " + SocketUtils.toString(serverSocket.getLocalSocketAddress()));

			while (this.isRunEnabled()) {
				Socket socketClient = serverSocket.accept();

				this.getLogger().log(Level.INFO, "Connection from: " + SocketUtils.toString(socketClient.getLocalSocketAddress()));

				Socket socketServer = null;

				if (this.proxy != null) {
					SocketAddress proxyAddress = new InetSocketAddress(this.proxy.getHost(), this.proxy.getPort());
					Proxy proxy = new Proxy(Type.SOCKS, proxyAddress);
					SocketAddress address = new InetSocketAddress(this.redirect.getHost(), this.redirect.getPort());

					socketServer = new Socket(proxy);
					socketServer.setKeepAlive(true);
					socketServer.connect(address, TCPRedirect.TIMEOUT);
				} else {
					socketServer = new Socket(this.redirect.getHost(), this.redirect.getPort());
					socketServer.setKeepAlive(true);
					socketServer.setSoTimeout(TCPRedirect.TIMEOUT);
				}

				Thread t1 = new Thread(new TCPRedirectHandler(socketClient, socketServer));
				Thread t2 = new Thread(new TCPRedirectHandler(socketServer, socketClient));

				t1.start();
				t2.start();
			}
		} catch (IOException e) {
			this.getLogger().log(Level.WARNING, e.getMessage(), e);
		}
	}

}
